package com.piggy.logi.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.piggy.logi.sys.domain.LogiWaybillGoodSource;
import com.piggy.logi.sys.mapper.LogiWaybillGoodSourceMapper;
import com.piggy.logi.sys.service.ILogiWaybillGoodSourceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class LogiWaybillGoodSourceServiceImpl extends ServiceImpl<LogiWaybillGoodSourceMapper, LogiWaybillGoodSource> implements ILogiWaybillGoodSourceService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateByWaybillId(Long waybillId, List<LogiWaybillGoodSource> boList) {
        if (CollUtil.isEmpty(boList)) {
            baseMapper.removeByWaybillId(waybillId);
        }
        List<LogiWaybillGoodSource> listDb = baseMapper.selectByWaybillIds(Lists.newArrayList(waybillId));

        List<LogiWaybillGoodSource> updates = boList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        Set<Long> updateIds = updates.stream().map(LogiWaybillGoodSource::getId).collect(Collectors.toSet());
        List<LogiWaybillGoodSource> adds = boList.stream().filter(item -> item.getId() == null).collect(Collectors.toList());
        List<Long> removeIds = listDb.stream().map(LogiWaybillGoodSource::getId)
                .filter(id -> !updateIds.contains(id)).distinct().collect(Collectors.toList());

        this.updateBatchById(updates);
        this.saveBatch(adds);
        this.removeBatchByIds(removeIds);
    }

    @Override
    public List<LogiWaybillGoodSource> getByWaybillIds(List<Long> waybillIds) {
        if (CollUtil.isEmpty(waybillIds)) {
            return CollUtil.newArrayList();
        }
        return baseMapper.selectByWaybillIds(waybillIds);
    }
}
